package com.zwh.service;


import com.zwh.dao.UserDao;
import com.zwh.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

@Service
@Transactional//控制事务
public class UserServiceImpl implements UserService{
    private UserDao userDao;//就连接dao层

    @Autowired//还是使用构造注入
    public UserServiceImpl(UserDao userDao) {//这里要是找不到UserDao类型的bean就在对应的Dao接口加上@Repository注解
        this.userDao = userDao;
    }

    @Override
    public void regist(User user) {
        //根据用户名查询数据库中是否存在该用户
        User userDB = userDao.findByUserName(user.getUsername());
        if (!ObjectUtils.isEmpty(userDB)) throw new RuntimeException("当前用户已被注册");
        //注册用户
        userDao.save(user);
    }

    @Override
    public User login(String username, String password) {

        User user = userDao.findByUserName(username);
        if (ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名不正确");
        //比较密码，因为这里没有对密码进行加密，所以直接比较即可
        // 获取数据库中存储的密码,user.getPassword()
        //String storedPassword = user.getPassword();
        if (!user.getPassword().equals(password)) throw new RuntimeException("密码输入错误");

        return user;
    }
}
